/**
 * Created by guany on 2017/1/8.
 */
var util = require("../util/util");
var crypto = require("crypto");
var uuid = require("uuid");
var moment = require("moment");
var url = require("url");
var fs = require("fs");
var path = require("path");
var multiparty = require('multiparty');
var logger = require("../logger");

// 实现与MySQL交互
var mysql = require('mysql');
var $conf = require('../conf/conf');
var $sqls = require('../sqls/sqls');

// 使用连接池，提升性能
var pool  = mysql.createPool($conf.mysql);

// 向前台返回JSON方法的简单封装
var jsonWrite = function (res, ret) {
    if(typeof ret === 'undefined') {
        res.json({
            code:'1',
            msg: '操作失败'
        });
    } else {
        res.json(ret);
    }
};

//返回正确
var setOK = function (_result,result,message,code) {
    _result.code = util.isEmpty(code)?200:code;
    _result.message = util.isEmpty(message)?"":message;
    _result.result = util.isEmpty(result)?{}:result;
    _result.status = "OK";
}
//返回错误
var setError = function (_result,message,code) {
    _result.code = util.isEmpty(code)?401:code;
    _result.message = util.isEmpty(message)?"":message;
    _result.result = {};
    _result.status = "ERROR";
}

var dao = {
    login: function (req, res, next) {
        pool.getConnection(function(err, connection) {
            // 获取前台页面传过来的参数
            var param = req.body;
            var _result = {};
            var password = param.password;
            var hasher = crypto.createHash("md5");
            hasher.update(password);
            var pwd = hasher.digest('hex');
            connection.query($sqls.login, [param.userName, pwd], function (err, result) {
                if (util.isEmpty(err) && result) {
                    dao.getMenuCodeByID(req, res, next,result[0])
                } else {
                    _result.code = 401;
                    _result.message = "";
                    _result.result = {};
                    _result.status = "ERROR";
                }
                // 释放连接
                connection.release();
            });
        });
    },
    getMenuCodeByID:function (req, res, next,params) {
        pool.getConnection(function(err, connection) {
            var param = params.role_id;
            var _result = {};
            connection.query($sqls.getMenuCodeByID, [param], function(err, result) {
                if(util.isEmpty(err) && result){
                    var codeList = [];
                    result.forEach(function(item,index){
                        codeList.push(item.code);
                    });
                    _result.code = 200;
                    _result.message = "";
                    _result.result = {
                        depId: params.dep_id,
                        depName:params.dep_name,
                        menuCode:codeList,
                        realName: params.real_name,
                        roleCode:params.role_code,
                        roleId: params.role_id,
                        roleName:params.role_name,
                        userId: params.id_num,
                        userName: params.user_name
                    };
                    _result.status = "OK";
                    req.session.roleid =  params.role_id;
                    req.session.username = params.user_name;
                    req.session.userid = params.id;
                    req.session.depid = params.dep_id;
                }else{
                    _result.code = 401;
                    _result.message = "";
                    _result.result = {};
                    _result.status = "ERROR";
                    req.session = {};
                }
                // 以json形式，把操作结果返回给前台页面
                jsonWrite(res, _result);
                // 释放连接
                connection.release();
            });
        });
    },
    findAllMenu:function (req, res, next) {
        pool.getConnection(function(err, connection) {
            // 获取session值
            var role_id = req.session.roleid;
            var _result = {};
            if(util.isInteger(role_id)){
                connection.query($sqls.findAllMenu, [role_id], function(err, result) {
                    if (util.isEmpty(err) && result) {
                        _result.code = 200;
                        _result.message = "";
                        var resultobject = {};
                        result.forEach(function(item,index){
                            var obj = {};
                            obj["name"] = item.name;
                            obj["id"] = item.id;
                            obj["pId"] = item.p_id;
                            resultobject[item.code] = obj;
                        });
                        _result.result = JSON.stringify(resultobject);
                        _result.status = "OK";
                    } else {
                        _result.code = 401;
                        _result.message = "";
                        _result.result = {};
                        _result.status = "ERROR";
                    }
                    jsonWrite(res, _result);
                    connection.release();
                });
            }else{
                _result.code = 401;
                _result.message = "网页已过期";
                _result.result = {};
                _result.status = "ERROR";
                jsonWrite(res, _result);
                connection.release();
            }
        });
    },
    selecOne: function (req, res, next) {
        pool.getConnection(function(err, connection) {
            var _result = {};
            connection.query($sqls.selecOne, [], function(err, result) {
                if (util.isEmpty(err) && result.length == 2) {
                    _result.code = 200;
                    _result.message = "";
                    var resultobject = {};
                    var result1 = result[0][0];
                    var result2 = result[1];
                    resultobject["id"] = result1.id;
                    resultobject["logoFileId"] = result1.logo_file_id;
                    resultobject["nameEn"] = result1.name_en;
                    resultobject["nameZh"] = result1.name_zh;
                    resultobject["principal"] = result1.principal;
                    resultobject["tel"] = result1.tel;
                    resultobject["fax"] = result1.fax;
                    var list = [];
                    result2.forEach(function(item,index){
                        list.push(item.id);
                    });
                    resultobject["homeImgs_Ids"] = list;
                    _result.result = resultobject;
                    _result.status = "OK";
                } else {
                    _result.code = 401;
                    _result.message = "";
                    _result.result = {};
                    _result.status = "ERROR";
                }
                jsonWrite(res, _result);
                connection.release();
            });
        });
    },
    visitorList: function (req, res, next) {
        pool.getConnection(function(err, connection) {
            //获取参数
            var params = req.query;
            var _result = {};
            if(!util.isEmpty(params) && !util.isEmpty(params.pageNum) && !util.isEmpty(params.pageSize)){
                var pageNum = parseInt(params.pageNum);
                var pageSize = parseInt(params.pageSize);
                if(pageNum >= 1 && pageSize >= 1){
                    connection.query($sqls.visitorList, [(pageNum-1)*pageSize,pageSize], function(err, result) {
                        if (util.isEmpty(err) && result.length == 2){
                            _result.code = 200;
                            _result.message = "";
                            var result1 = result[0][0];
                            var result2 = result[1];
                            var resultobj = {};
                            var pagination2 = {};
                            pagination2["begin"] = pageSize*(pageNum-1);
                            pagination2["currentPage"] = pageNum;
                            pagination2["end"] = pageSize*pageNum-1;
                            pagination2["pageSize"] = pageSize;
                            pagination2["totalRecords"] = result1.total;
                            pagination2["totalPage"] = parseInt(result1.total/10)+1;
                            resultobj.pagination2 = pagination2;
                            var list = [];
                            result2.forEach(function(item,index){
                                var obj = {};
                                obj["name"] = item.name;
                                obj["state"] = item.state;
                                obj["visittime"] = item.plan_start_time + " ~ " + item.plan_end_time;
                                list.push(obj);
                            });
                            resultobj.results = list;
                            _result.result = resultobj;
                            _result.status = "OK";
                        } else {
                            _result.code = 401;
                            _result.message = "";
                            _result.result = {};
                            _result.status = "ERROR";
                        }
                        jsonWrite(res, _result);
                        connection.release();
                    });
                }else{
                    _result.code = 401;
                    _result.message = "参数不正确";
                    _result.result = {};
                    _result.status = "ERROR";
                    jsonWrite(res, _result);
                    connection.release();
                }
            }else{
                _result.code = 401;
                _result.message = "参数为空";
                _result.result = {};
                _result.status = "ERROR";
                jsonWrite(res, _result);
                connection.release();
            }
        });
    },
    attendancdList: function (req, res, next) {
        pool.getConnection(function(err, connection) {
            //获取参数
            var params = req.query;
            var _result = {};
            if(!util.isEmpty(params) && !util.isEmpty(params.pageNum) && !util.isEmpty(params.pageSize)){
                var pageNum = parseInt(params.pageNum);
                var pageSize = parseInt(params.pageSize);
                if(pageNum >= 1 && pageSize >= 1){
                    var today_1 = moment().format("YYYY-MM-DD 00:00:00");
                    var today_2 = moment().format("YYYY-MM-DD 23:59:59");
                    connection.query($sqls.attendancdList, [today_1,today_2,today_1,today_2,(pageNum-1)*pageSize,pageSize], function(err, result) {
                        if (util.isEmpty(err) && result.length == 2){
                            _result.code = 200;
                            _result.message = "";
                            var resultobj = {};
                            var result1 = result[0];
                            var result2 = result[1];
                            var pagination2 = {};
                            pagination2["begin"] = pageSize*(pageNum-1);
                            pagination2["currentPage"] = pageNum;
                            pagination2["end"] = pageSize*pageNum-1;
                            pagination2["pageSize"] = pageSize;
                            pagination2["totalRecords"] = result1.length;
                            pagination2["totalPage"] = parseInt(result1.length/10)+1;
                            resultobj.pagination2 = pagination2;
                            var list = [];
                            result2.forEach(function(item,index){
                                var obj = {};
                                obj["checkIn"] = moment(item.first_time).valueOf();
                                obj["checkOut"] = moment(item.last_time).valueOf();
                                obj["checkType"] = item.validate_way;
                                obj["depId"] = item.dep_id;
                                obj["depName"] = item.name;
                                obj["id"] = item.id;
                                obj["recordDate"] = moment(moment().format("YYYY-MM-DD"),"YYYY-MM-DD").valueOf();
                                obj["userId"] = item.user_id;
                                obj["userNum"] = item.id_num;
                                obj["userRealName"] = item.real_name;
                                list.push(obj);
                            });
                            resultobj.results = list;
                            _result.result = resultobj;
                            _result.status = "OK";
                        } else {
                            _result.code = 401;
                            _result.message = "";
                            _result.result = {};
                            _result.status = "ERROR";
                        }
                        jsonWrite(res, _result);
                        connection.release();
                    });
                }else{
                    _result.code = 401;
                    _result.message = "参数不正确";
                    _result.result = {};
                    _result.status = "ERROR";
                    jsonWrite(res, _result);
                    connection.release();
                }
            }else{
                _result.code = 401;
                _result.message = "参数为空";
                _result.result = {};
                _result.status = "ERROR";
                jsonWrite(res, _result);
                connection.release();
            }
        });
    },
    getImg: function (req, res, next) {
        pool.getConnection(function(err, connection) {
            //获取参数
            var params = req.query;
            var _result = {};
            if(!util.isEmpty(params) && !util.isEmpty(params.id)){
                var imageid = parseInt(params.id);
                connection.query($sqls.getImg, [imageid], function(err, result) {
                    if (util.isEmpty(err) && result){
                        var content =  fs.readFileSync(path.join(__dirname, '../public/images/'+result[0].file_path),"binary");
                        res.end(content,"binary");
                    } else {
                        _result.code = 401;
                        _result.message = "";
                        _result.result = {};
                        _result.status = "ERROR";
                        jsonWrite(res, _result);
                    }
                    connection.release();
                });
            }else{
                _result.code = 401;
                _result.message = "参数为空";
                _result.result = {};
                _result.status = "ERROR";
                jsonWrite(res, _result);
                connection.release();
            }
        });
    },
    save: function (req, res, next) {
        //生成multiparty对象，并配置上传目标路径
        var form = new multiparty.Form({uploadDir: './public/images/'});
        //上传完成后处理
        form.parse(req, function(err, fields, files) {
            var _result = {};
            if(err){
                _result.code = 401;
                _result.message = "upload error" + err;
                _result.result = {};
                _result.status = "ERROR";
                jsonWrite(res, _result);
            }else{
                var tempFlag = -1;
                var count = 1,index = 0;
                for(var i=0;i<files.length;i++){
                    count *= files[i];
                }
                for(var key in files){
                    var list = files[key];
                    list.forEach(function(item,index){
                        var uploadedPath = item.path;
                        var filename = item.originalFilename;
                        var dstPath = './public/images/' + key + "/" + filename;
                        //重命名文件
                        fs.rename(uploadedPath, dstPath, function(err) {
                            if(err){
                                logger.info('upload error: ' + err);
                                index++;
                            }else{
                                logger.info('upload ok');
                                //插入数据
                                pool.getConnection(function(err, connection) {
                                    connection.query($sqls.getCompanyID, [], function(err, result) {
                                        var companyid;
                                        if (util.isEmpty(err) && result){
                                            companyid = result[0].id;
                                        } else {
                                            companyid = null;
                                        }
                                        //获取参数
                                        var fileextlist = filename.split(".");
                                        var fileext = fileextlist[fileextlist.length-1];
                                        connection.query($sqls.saveImg, [filename,key+"/"+filename,fileext,key=="homeImgs"?1:0,companyid,req.session.userid,moment().format("YYYY-MM-DD HH:mm:ss")], function(err, result) {
                                            if (util.isEmpty(err) && result){
                                                tempFlag = 1;
                                            } else {
                                                tempFlag = 0;
                                            }
                                            connection.release();
                                            index++;
                                            if(count == index){
                                                if(tempFlag == 1){
                                                    _result.code = 200;
                                                    _result.message = "upload ok";
                                                    _result.result = {};
                                                    _result.status = "OK";
                                                }else{
                                                    _result.code = 401;
                                                    _result.message = "upload error" + err;
                                                    _result.result = {};
                                                    _result.status = "ERROR";
                                                }
                                                jsonWrite(res, _result);
                                            }
                                        });
                                    });
                                });
                            }
                        });
                    });
                }
            }
        });
    },
    deleteImg: function (req, res, next) {
        pool.getConnection(function(err, connection) {
            //获取参数
            var params = req.query;
            var _result = {};
            if(!util.isEmpty(params) && !util.isEmpty(params.id)){
                var imageid = parseInt(params.id);
                connection.query($sqls.queryImgByID, [imageid], function(err, result) {
                    if (util.isEmpty(err) && result){
                        var falepath = result[0].file_path;
                        fs.unlink("./public/images/"+falepath,function (err) {
                            if(err){
                                _result.code = 401;
                                _result.message = "";
                                _result.result = {};
                                _result.status = "ERROR";
                                jsonWrite(res, _result);
                                connection.release();
                            }else{
                                connection.query($sqls.deleteImg, [imageid], function(err, result) {
                                    if (util.isEmpty(err) && result){
                                        _result.code = 200;
                                        _result.message = "";
                                        _result.result = {};
                                        _result.status = "OK";
                                    } else {
                                        _result.code = 401;
                                        _result.message = "";
                                        _result.result = {};
                                        _result.status = "ERROR";
                                    }
                                    jsonWrite(res, _result);
                                    connection.release();
                                });
                            }
                        });
                    } else {
                        _result.code = 401;
                        _result.message = "";
                        _result.result = {};
                        _result.status = "ERROR";
                        jsonWrite(res, _result);
                        connection.release();
                    }
                });
            }else{
                _result.code = 401;
                _result.message = "参数为空";
                _result.result = {};
                _result.status = "ERROR";
                jsonWrite(res, _result);
                connection.release();
            }
        });
    },
    getInfo: function (req, res, next) {
        pool.getConnection(function(err, connection) {
            //获取参数
            var depid = req.session.depid;
            var _result = {};
            if(util.isEmpty(depid)){
                setError(_result,"网页已过期");
                jsonWrite(res,_result);
                connection.release();
            }else{
                connection.query($sqls.getInfo, [depid,depid], function(err, result) {
                    if (util.isEmpty(err) && result){
                        var list = [];
                        result.forEach(function (item,index) {
                            var obj = {};
                            obj["count"] = item.count;
                            obj["id"] = item.id;
                            obj["leader"] = item.leader;
                            obj["leaderName"] = item.leaderName;
                            obj["name"] = item.name;
                            obj["pId"] = item.p_id;
                            obj["sort"] = item.sort;
                            list.push(obj);
                        });
                        setOK(_result,list);
                        jsonWrite(res,_result);
                        connection.release();
                    } else {
                        setError(_result,"获取数据失败");
                        jsonWrite(res,_result);
                        connection.release();
                    }
                });
            }
        });
    },
    selectChildDep:function (req, res, next) {
        pool.getConnection(function(err, connection) {
            //获取参数
            var depid = req.query.id;
            var _result = {};
            if(util.isEmpty(depid)){
                setError(_result,"网页已过期");
                jsonWrite(res,_result);
                connection.release();
            }else{
                connection.query($sqls.selectChildDep, [depid], function(err, result) {
                    if (util.isEmpty(err) && result){
                        var list = [];
                        result.forEach(function (item,index) {
                            var obj = {};
                            obj["createTime"] = item.create_time;
                            obj["depNum"] = item.dep_num;
                            obj["id"] = item.id;
                            obj["isDisabled"] = item.is_disabled;
                            obj["leader"] = item.leader;
                            obj["name"] = item.name;
                            obj["pId"] = item.p_id;
                            obj["ruleId"] = item.rule_id;
                            obj["sort"] = item.sort;
                            list.push(obj);
                        });
                        setOK(_result,list);
                        jsonWrite(res,_result);
                        connection.release();
                    } else {
                        setError(_result,"获取数据失败");
                        jsonWrite(res,_result);
                        connection.release();
                    }
                });
            }
        });
    },
    findUserInfoByDepId:function (req, res, next) {
        pool.getConnection(function(err, connection) {
            //获取参数
            var depid = req.query.id;
            var _result = {};
            if(util.isEmpty(depid)){
                setError(_result,"网页已过期");
                jsonWrite(res,_result);
                connection.release();
            }else{
                connection.query($sqls.findUserInfoByDepId, [depid], function(err, result) {
                    if (util.isEmpty(err) && result){
                        var list = [];
                        result.forEach(function (item,index) {
                            var obj = {};
                            obj["createTime"] = item.create_time;
                            obj["depId"] = item.dep_id;
                            obj["faceId"] = item.face_id;
                            obj["fingerId"] = item.finger_id;
                            obj["id"] = item.id;
                            obj["idCard"] = item.id_card;
                            obj["idNum"] = item.id_num;
                            obj["isDisabled"] = item.is_disabled;
                            obj["password"] = item.password;
                            obj["position"] = item.position;
                            obj["realName"] = item.real_name;
                            obj["roleId"] = item.role_id;
                            obj["subPhone"] = item.sub_phone;
                            obj["tel"] = item.tel;
                            obj["updateBy"] = item.update_by;
                            obj["updateTime"] = item.update_time;
                            obj["userName"] = item.user_name;
                            list.push(obj);
                        });
                        setOK(_result,list);
                        jsonWrite(res,_result);
                        connection.release();
                    } else {
                        setError(_result,"获取数据失败");
                        jsonWrite(res,_result);
                        connection.release();
                    }
                });
            }
        });
    },
    selectList:function (req, res, next) {
        pool.getConnection(function(err, connection) {
            //获取参数
            var depid = req.session.depid;
            var _result = {};
            if(util.isEmpty(depid)){
                setError(_result,"网页已过期");
                jsonWrite(res,_result);
                connection.release();
            }else{
                connection.query($sqls.selectList, [depid], function(err, result) {
                    if (util.isEmpty(err) && result){
                        var list = [];
                        result.forEach(function (item,index) {
                            var obj = {};
                            obj["createTime"] = item.create_time;
                            obj["depNum"] = item.dep_num;
                            obj["id"] = item.id;
                            obj["isDisabled"] = item.is_disabled;
                            obj["leader"] = item.leader;
                            obj["name"] = item.name;
                            obj["pId"] = item.p_id;
                            obj["ruleId"] = item.rule_id;
                            obj["sort"] = item.sort;
                            list.push(obj);
                        });
                        setOK(_result,list);
                        jsonWrite(res,_result);
                        connection.release();
                    } else {
                        setError(_result,"获取数据失败");
                        jsonWrite(res,_result);
                        connection.release();
                    }
                });
            }
        });
    },
    fetchList:function (req, res, next) {
        pool.getConnection(function(err, connection) {
            //获取参数
            var depid = parseInt(req.session.depid);
            var params = req.query;
            var wherestring = "";
            var _result = {};
            if(util.isEmpty(depid)){
                setError(_result,"网页已过期");
                jsonWrite(res,_result);
                connection.release();
            }else{
                var pagenum = 1;
                var pagesize = 10;
                if(params){
                    if(!util.isEmpty(params.depId)){
                        var _dep_id = parseInt(params.depId);
                        wherestring += "dep_id=" + _dep_id + " and ";
                    }
                    if(!util.isEmpty(params.department)){
                        wherestring += "department like '%" + params.department + "%' and ";
                    }
                    if(!util.isEmpty(params.inviterName)){
                        wherestring += "inviter_name like '%" + params.inviterName + "%' and ";
                    }
                    if(!util.isEmpty(params.name)){
                        wherestring += "name like '%" + params.name + "%' and ";
                    }
                    if(!util.isEmpty(params.state)){
                        var _state = parseInt(params.state);
                        wherestring += "state=" + _state + " and ";
                    }
                }
                if(wherestring){
                    wherestring = "where " + wherestring.substr(0,wherestring.length-5);
                }
                var sqlstring = $sqls.fetchListCount + wherestring + ";" + $sqls.fetchList + wherestring + " limit ?,?";
                connection.query(sqlstring, [depid,depid,depid,depid,(pagenum-1)*pagesize,pagesize], function(err, result) {
                    if (util.isEmpty(err) && result.length == 2){
                        var resultobj = {};
                        var result1 = result[0][0];
                        var result2 = result[1];
                        var pagination2 = {};
                        pagination2["begin"] = pagesize*(pagenum-1);
                        pagination2["currentPage"] = pagenum;
                        pagination2["end"] = pagesize*pagenum-1;
                        pagination2["pageSize"] = pagesize;
                        pagination2["totalRecords"] = result1.total;
                        pagination2["totalPage"] = parseInt(result1.total/10)+1;
                        resultobj.pagination2 = pagination2;
                        var list = [];
                        result2.forEach(function(item,index){
                            var obj = {};
                            obj["createBy"] = item.create_by;
                            obj["createName"] = item.create_name;
                            obj["createTime"] = moment(item.create_time,"YYYY-MM-DD HH:mm:ss").valueOf();
                            obj["depId"] = item.dep_id;
                            obj["depName"] = item.dep_name;
                            obj["department"] = item.department;
                            obj["id"] = item.id;
                            obj["idCard"] = item.id_card;
                            obj["inviter"] = item.inviter;
                            obj["inviterName"] = item.inviter_name;
                            obj["name"] = item.name;
                            obj["planEndTime"] = moment(item.plan_end_time,"YYYY-MM-DD HH:mm:ss").valueOf();
                            obj["planStartTime"] = moment(item.plan_start_time,"YYYY-MM-DD HH:mm:ss").valueOf();
                            obj["reason"] = item.reason;
                            obj["sex"] = item.sex;
                            obj["state"] = item.state;
                            obj["tel"] = item.tel;
                            obj["type"] = item.type;
                            obj["undoReason"] = item.undo_reason;
                            obj["updateBy"] = item.update_by;
                            obj["updateTime"] = moment(item.update_time,"YYYY-MM-DD HH:mm:ss").valueOf();
                            list.push(obj);
                        });
                        resultobj.results = list;
                        setOK(_result,resultobj);
                        jsonWrite(res,_result);
                        connection.release();
                    } else {
                        setError(_result,"获取数据失败");
                        jsonWrite(res,_result);
                        connection.release();
                    }
                });
            }
        });
    }
};

module.exports = dao;